//
//  FriendRequestsViewController.swift
//  puretennis
//
//  Created by Derek Zheng on 12/9/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class FriendRequestsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var friendList: [NSMutableDictionary] = []
    
    var friendListView: UITableView = UITableView()
    
    var friendDetailsViewController = UserDetailsViewController()
    
    var friendsViewController: FriendsViewController?

    
    override func viewDidLoad() {
        self.initNavigation();
    }
    
    func initNavigation(){
        var backButton = UIButton();
        backButton.setImage(UIImage(named: "back"), forState: UIControlState.Normal);
        backButton.showsTouchWhenHighlighted = true;
        backButton.sizeToFit();
        backButton.addTarget(self, action: Selector("back:"), forControlEvents: UIControlEvents.TouchUpInside);
        var backBarButton = UIBarButtonItem(customView: backButton);
        self.navigationItem.leftBarButtonItem = backBarButton;
    }
    
    func back(sender:UIButton){
        self.navigationController?.popViewControllerAnimated(true);
    }
    
    override func viewDidAppear(animated: Bool) {
        self.navigationItem.titleView = ViewUtils.titleView("好友请求")
    }
    
    override func viewWillAppear(animated: Bool) {
        ViewUtils.addBackgroundView(self)
        
        friendListView.separatorStyle = UITableViewCellSeparatorStyle.None
        friendListView.backgroundColor = UIColor.clearColor()
        friendListView.delegate = self
        friendListView.dataSource = self
        
        var navigationBarHeight = (self.navigationController?.navigationBar.frame.height)! + ViewUtils.statusBarHeight();
        friendListView.frame.origin = CGPoint(x: 0, y: navigationBarHeight);
        friendListView.frame.size = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height * 0.7);
        self.view.addSubview(friendListView);
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return friendList.count;
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        var request = friendList[indexPath.row] as NSMutableDictionary;
        
        var friend = request.objectForKey("sender") as NSMutableDictionary

        
        var guid = friend.objectForKey("guid") as String
        friendDetailsViewController.guid = guid
        
        friendDetailsViewController.loadUserDetails()
        self.navigationController?.pushViewController(self.friendDetailsViewController, animated: true)
        
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        var request = friendList[indexPath.row] as NSMutableDictionary;
        
        var friend = request.objectForKey("sender") as NSMutableDictionary
        
        var guid = friend.objectForKey("guid") as String
        
        var cell = UITableViewCell()
        
        
        cell.backgroundColor = UIColor.clearColor()
        cell.backgroundView = UIImageView(image: UIImage(named: "cell_bg"));
        cell.selectionStyle = UITableViewCellSelectionStyle.None
        var arrow = UIImageView(image: UIImage(named: "I"));
        
        arrow.frame.origin.x = cell.contentView.frame.origin.x + cell.contentView.frame.width - arrow.frame.width - 5;
        arrow.frame.origin.y += (cell.contentView.frame.height - arrow.frame.height) / 2
        
        cell.contentView.addSubview(arrow);
        
        var userImage: UIImageView!
        var imageData = friend.objectForKey("imageBase64Byte") as String
        
        
        if(!imageData.isEmpty){
            let decodedData = NSData(base64EncodedString: imageData, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
            
            userImage = UIImageView(image: UIImage(data: decodedData!))
        }else{
            userImage = UIImageView(image: UIImage(named: "avatar"))
        }
        
        userImage.layer.cornerRadius = 20
        userImage.layer.masksToBounds = true
        userImage.frame.size = CGSize(width: cell.frame.height * 0.9, height: cell.frame.height * 0.9)
        userImage.frame.origin.x = 5;
        userImage.frame.origin.y += (cell.contentView.frame.height - userImage.frame.height) / 2
        
        
        cell.indentationWidth = userImage.frame.width
        cell.indentationLevel = 1
        cell.textLabel!.text = (friend.objectForKey("nickname")) as? String;
        cell.textLabel!.font = Utils.fontHupo(16);
        cell.textLabel!.textColor = UIColor.whiteColor()
        cell.textLabel!.backgroundColor = UIColor.clearColor()
        
        
        cell.contentView.addSubview(userImage)
        
        
        
        return cell;
    }
    
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool{
        return true;
    }
    
    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
        
        let deleteRequestAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "",handler:rejectAddFriendRequest);
        
        var deleteImage = ImageUtils.stretchableImage("close_in_row")
        
        let acceptRequestAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "",handler:acceptAddFriendRequest);
        
        var acceptImage = ImageUtils.stretchableImage("confirm")
        
        deleteRequestAction.backgroundColor = UIColor(patternImage: deleteImage)
        acceptRequestAction.backgroundColor = UIColor(patternImage: acceptImage)
        
        return [deleteRequestAction, acceptRequestAction];
    }
    
    func acceptAddFriendRequest(tableViewRowAction:UITableViewRowAction!,indexPath:NSIndexPath!){
        var request = friendList[indexPath.row] as NSDictionary
        var requestGuid = request.objectForKey("guid") as String
        var body = NSMutableDictionary()
        body.setObject(requestGuid, forKey: "guid")
       
        var url = "/api/v1/friends/request/accept"
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: body, successHandle: { (response) -> Void in
            self.friendList.removeAtIndex(indexPath.row)
            self.friendListView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
            self.friendsViewController?.loadFriends();
            self.updateTabBarBadge();
        }, errorHandle: { (error) -> Void in
            
        })
    }
    
    func rejectAddFriendRequest(tableViewRowAction:UITableViewRowAction!,indexPath:NSIndexPath!){
        var request = friendList[indexPath.row] as NSDictionary
        var requestGuid = request.objectForKey("guid") as String
        var body = NSMutableDictionary()
        body.setObject(requestGuid, forKey: "guid")
    
        var url = "/api/v1/friends/request/reject"
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: body, successHandle: { (response) -> Void in
            self.friendList.removeAtIndex(indexPath.row)
            self.friendListView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
            self.updateTabBarBadge();
            }, errorHandle: { (error) -> Void in
        })
    }
    
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
        
    }
    
    func loadFriendRequests(){
        self.processing();
        var url = "/api/v1/friends/requests"
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            self.friendList = response as [NSMutableDictionary]
            self.friendListView.reloadData();
            self.processComplete();
        }, errorHandle: { (error) -> Void in
            self.processComplete();
        })
    }
}
